import { Component, ComponentUnitType, useComponentsStore } from "@/stores/edit-pages-store";
import { useEffect, useState } from "react";
import {useComponentConfigStore} from "@/stores/low-editor-comps-conf";
import type { TreeDataNode } from 'antd';
export interface CompTreeDataNode extends TreeDataNode{
  id: string,
  name: string,
  editRegion?: ComponentUnitType
}
export function getMainOutlineData(withDefinitions: boolean = false, selectStrict: boolean = false) {
  const [treeData, setTreeData] = useState<CompTreeDataNode[]>([])
  const { schema, popEditing, curPopTarget } = useComponentsStore();
  const {flatComponentConfig} = useComponentConfigStore();
  const componentConfigGroup = flatComponentConfig()
  const labelObj: Record<ComponentUnitType, string> = {
    aside: "边栏",
    body: "内容区",
    buttonGroup: "操作区",
    footer: "底部栏",
    header:"标题栏",
    definitions:"弹窗列表"
  }
  function constructTreeData(){
    const targetValue = popEditing ? curPopTarget : schema
    if(!targetValue)return []
    function loop(schemaArr: Component[]){
      return schemaArr.map(ele=>{
        const {name, id, desc} = ele
        const obj:CompTreeDataNode = {
          title: desc,
          key: ele.id,
          id,
          name
        }
        const componentConf = componentConfigGroup[name]
        const accept = componentConf.accept
        
        if(accept){
          const aLen = Object.keys(accept).length
          if(aLen===1){
            const aKey = Object.keys(accept)[0] as ComponentUnitType
            if(Array.isArray(ele[aKey]) && ele[aKey].length>0){obj.children=[]}
            obj.children?.push(...loop(ele[aKey] as Component[]))
            obj.editRegion = aKey
          }else{
            const children:CompTreeDataNode[] = []
            for(const key in accept){
              if(ele.name==="Page"){
                if(key === "aside"){
                  const showAside = ele?.props?.showAside || false;
                  if(!showAside)continue
                }else if(key === "definitions"){
                  if(!withDefinitions)continue
                }
              }
              if(ele?.[key as ComponentUnitType]){
                children.push({
                  key: `${ele.id}_${key}`,
                  title: labelObj[key as ComponentUnitType],
                  children: loop(ele[key as ComponentUnitType] as Component[]),
                  id: ele.id,
                  name: ele.name,
                  editRegion: key as ComponentUnitType,
                  ...selectStrict && {disabled: true}
                })
              }
            }
            obj.children = children
          }
        }
        return obj
      })
    }
    return loop([targetValue])
  }
  useEffect(()=>{
    const data= constructTreeData()
    setTreeData(data)
  }, [schema, popEditing])
  //处理侧边栏,如果隐藏了，这部分数据不应该展示
  return {treeData}
}
